package com.example.demo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.demo.model.ProjectEmployee;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @author: jamesfu
 * @date: 2024-01-09 20:25
 */
@Slf4j
public class DemoApplicationTests2 {

    Map<String, List<Integer>> p1 = null;
    Map<Integer, String> p2 = null;

    @Test
    public void testListFileNames() throws Exception {
        String dir = "/Users/jamesfu/Downloads/2020年派沃特";
        List<String> strings = FileUtil.listFileNames(dir);
        log.info("  {}", strings);
        for (String fileName : strings) {
            if (fileName.startsWith(".~") || fileName.startsWith(".DS_Store")) {
                continue;
            }
            String extName = FileUtil.extName(fileName);
            String fileNameWithoutExt = fileName.replace("." + extName, "");
            log.info("file {}", fileName);
            p1 = null;
            p2 = null;
            doProcess(dir, fileNameWithoutExt);
        }
    }

    @Test
    public void test5() throws Exception {
        String fileName = "2020.11月人工分配-完成";
        String dir = "/Users/jamesfu/Downloads";
        doProcess(dir, fileName);
    }

    private void doProcess(String dir, String fileName) throws IOException {
        @Cleanup
        FileInputStream stream = new FileInputStream(dir + String.format("/%s.xlsx", fileName));

        List<ProjectEmployee> resultList = new ArrayList<>();
        EasyExcel.read(stream, new AnalysisEventListener<Map<Integer, String>>() {
                    @Override
                    public void invoke(Map<Integer, String> row, AnalysisContext analysisContext) {
                        log.info("data is {}", row);
                        if (p1 == null) {
                            p1 = new LinkedHashMap<>();
                            row.forEach((key, value) -> {
                                        p1.putIfAbsent(value, new ArrayList<>());
                                        p1.get(value).add(key);
                                    }
                            );
                        } else if (p2 == null) {
                            p2 = row;
                        } else {
                            Integer nameIndex = p1.get("姓名").get(0);
                            String name = row.get(nameIndex);
                            if (StrUtil.isBlank(name)) {
                                return;
                            }

                            Integer departmentIndex = p1.get("部门").get(0);
                            String departmentName = row.get(departmentIndex);

                            List<Integer> gongShiIndex = p1.get("工时");
                            List<Integer> gongZiIndex = p1.get("工资");
                            List<Integer> sheBaoIndex = p1.get("社保");
                            List<Integer> gongJiJinIndex = p1.get("公积金");
                            Map<String, ProjectEmployee> projectNoMap = new HashMap<>();
                            // 处理工时
                            gongShiIndex.forEach(index -> {
                                String projectNo = p2.get(index);
                                if (StrUtil.isNotBlank(projectNo) && projectNo.toUpperCase().contains("YF")) {
                                    String gongShi = row.get(index);
                                    if (StrUtil.isNotBlank(gongShi) && !gongShi.equals("-") && !gongShi.contains("- 0")) {
                                        projectNoMap.putIfAbsent(projectNo, new ProjectEmployee());
                                        ProjectEmployee projectEmployee = projectNoMap.get(projectNo);
                                        projectEmployee.setGongShi(gongShi);
                                    }
                                }
                            });

                            // 处理工资
                            gongZiIndex.forEach(index -> {
                                String projectNo = p2.get(index);
                                if (StrUtil.isNotBlank(projectNo) && projectNo.toUpperCase().contains("YF")) {
                                    String gongShi = row.get(index);
                                    if (StrUtil.isNotBlank(gongShi) && !gongShi.equals("-") && !gongShi.contains("- 0")) {
                                        projectNoMap.putIfAbsent(projectNo, new ProjectEmployee());
                                        ProjectEmployee projectEmployee = projectNoMap.get(projectNo);
                                        projectEmployee.setGongZi(gongShi);
                                    }
                                }
                            });

                            // 处理社保
                            sheBaoIndex.forEach(index -> {
                                String projectNo = p2.get(index);
                                if (StrUtil.isNotBlank(projectNo) && projectNo.toUpperCase().contains("YF")) {
                                    String gongShi = row.get(index);
                                    if (StrUtil.isNotBlank(gongShi) && !gongShi.equals("-") && !gongShi.contains("- 0")) {
                                        projectNoMap.putIfAbsent(projectNo, new ProjectEmployee());

                                        ProjectEmployee projectEmployee = projectNoMap.get(projectNo);
                                        projectEmployee.setSheBao(gongShi);
                                    }
                                }
                            });

                            // 处理公积金
                            gongJiJinIndex.forEach(index -> {
                                String projectNo = p2.get(index);
                                if (StrUtil.isNotBlank(projectNo) && projectNo.toUpperCase().contains("YF")) {
                                    String gongShi = row.get(index);
                                    if (StrUtil.isNotBlank(gongShi) && !gongShi.equals("-") && !gongShi.contains("- 0")) {
                                        projectNoMap.putIfAbsent(projectNo, new ProjectEmployee());
                                        ProjectEmployee projectEmployee = projectNoMap.get(projectNo);
                                        projectEmployee.setGongJiJin(gongShi);
                                    }
                                }
                            });

                            projectNoMap.forEach((projectNo, projectEmployee) -> {
                                projectEmployee.setDepartmentNo(departmentName);
                                projectEmployee.setEmployeeName(name);
                                projectEmployee.setProjectNo(projectNo);
                                String gongZi = projectEmployee.getGongZi();
                                if (StrUtil.isBlank(gongZi)) {
                                    gongZi = "0.00";
                                    projectEmployee.setGongZi(gongZi);
                                } else {
                                    projectEmployee.setGongZi(gongZi.replaceAll(",", ""));
                                }
                                String sheBao = projectEmployee.getSheBao();
                                if (StrUtil.isBlank(sheBao)) {
                                    sheBao = "0.00";
                                    projectEmployee.setSheBao(sheBao);
                                } else {
                                    projectEmployee.setSheBao(sheBao.replaceAll(",", ""));
                                }
                                String gongJiJin = projectEmployee.getGongJiJin();
                                if (StrUtil.isBlank(gongJiJin)) {
                                    gongJiJin = "0.00";
                                    projectEmployee.setGongJiJin(gongJiJin);
                                } else {
                                    projectEmployee.setGongJiJin(gongJiJin.replaceAll(",", ""));
                                }
                                BigDecimal heJi = new BigDecimal(gongZi.replaceAll(",", ""))
                                        .add(new BigDecimal(sheBao.replaceAll(",", "")))
                                        .add(new BigDecimal(gongJiJin.replaceAll(",", "")));
                                projectEmployee.setHeJi(heJi);
                                resultList.add(projectEmployee);
                            });
                        }
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        log.info("data is {}", resultList);
                    }
                }).sheet("人工分配明细表")
                .doRead();

        writeListToExcel2(resultList, dir, fileName);
    }


    private void writeListToExcel2(List<ProjectEmployee> dataList, String dir, String fileName) throws IOException {
        // 导出到文件
        FileOutputStream outputStream = new FileOutputStream(dir + String.format("/%s-%s.xlsx", "result", fileName));

        // 配置Excel文件信息
        ExportParams params = new ExportParams();
        params.setTitle("");
        params.setSheetName("项目人工成本明细");

        // 导出Excel表格
        Workbook workbook = ExcelExportUtil.exportExcel(params, ProjectEmployee.class, dataList);
        workbook.write(outputStream);

        // 关闭资源
        outputStream.close();
        workbook.close();
    }
}
